package com.example.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.example.utils.ResultVOUtil;

@ControllerAdvice
public class LoanMarketExceptionHandler {

	public static final String IMOOC_ERROR_VIEW = "freemarker/error";

	@ExceptionHandler(value = Exception.class)
	public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e)
			throws Exception {
		e.printStackTrace();

		System.out.println("捕获到异常啦!~");

		if (isAjax(request)) {
			return ResultVOUtil.error(-1, e.getMessage());
		} else {
			System.out.println(e.getMessage());
			System.out.println(request.getRequestURL());
			
			ModelAndView mav = new ModelAndView();
            mav.addObject("exception", e);
            mav.addObject("url", request.getRequestURL());
            mav.setViewName(IMOOC_ERROR_VIEW);
            return mav;
		}
	}

	public static boolean isAjax(HttpServletRequest httpRequest) {
		return (httpRequest.getHeader("X-Requested-With") != null
				&& "XMLHttpRequest".equals(httpRequest.getHeader("X-Requested-With").toString()));
	}

}
